package com.ainge.easystudy.sort;


import java.util.Arrays;

/**
 * 冒泡排序
 *
 * @author: Ainge
 * @Time: 2021/9/15 23:43
 */
public class BubbleSort {

    public static void main(String[] args) {

        int[] arr = new int[]{1, 3, 4, 0, 3, 2, 7, 10, 40, 5, 8, 3, 20};
        BubbleSort.sort(arr);
        System.out.println(Arrays.toString(arr));

    }


    public static void sort(int[] array) {
        if (array == null || array.length < 2) {
            return;
        }
        int location;
        int count = array.length - 1;
        for (int i = 0; i < array.length - 1; i++) {
            location = count;
            for (int j = 0; j < location; j++) {
                if (array[j] > array[j + 1]) {
                    swap(array, j, j + 1);
                    count = j; // j位置后面的已经有序了。
                }
            }
            if (location == count) {
                // count无变化了
                break;
            }
        }
    }

    private static void swap(int[] array, int i, int j) {
        if (i != j) {
            array[i] ^= array[j];
            array[j] ^= array[i];
            array[i] ^= array[j];
        }
    }
}
